import java.util.PriorityQueue;
import java.util.concurrent.PriorityBlockingQueue;

@SuppressWarnings({"all"})
class MyTask implements Comparable<MyTask>{
    // 任务具体要干啥
    private Runnable runnable;
    // 任务具体啥时候干， 保存任务要执行的毫秒级时间戳
    private long time;

    // after 是一个时间间隔，不是绝对的时间戳的值
    public MyTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    public void run() {
        runnable.run();
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTask o) {
        return (int) (this.time - o.time);
    }
}

@SuppressWarnings({"all"})
class MyTimer {
    // 定时器内部要能够存放多个任务
    private PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();

    public void schedule(Runnable runnable, long delay) {
        MyTask task = new MyTask(runnable, delay);
        queue.put(task);
        // 每次任务插入成功之后，都唤醒一下扫描线程，让线程重新检查一下队首的任务是否要执行
        synchronized (locker) {
            locker.notify();
        }
    }

    private Object locker = new Object();


    public MyTimer() {
        Thread t = new Thread(() -> {
            while (true) {
                try {
                    // 先取出队首元素
                    MyTask task = queue.take();
                    // 再比较一下当前这个任务时间到了没？
                    long curTime = System.currentTimeMillis();
                    if (curTime < task.getTime()) {
                        // 时间没到
                        queue.put(task);
                        synchronized (locker) {
                            locker.wait(task.getTime() - curTime);
                        }
                    } else {
                        // 时间到了
                        task.run();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t.start();
    }
}

@SuppressWarnings({"all"})
public class Demo2 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello timer");
            }
        }, 3000);
        System.out.println("main");
    }
}
